import APIS from '@/apis';
import URLS from '@/apis/APIUrlDefine';
import Const from '@/common/Const';
import request from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import { Upload, Button, Input, Divider, List, Space, Popover } from 'antd';

import { RcCustomRequestOptions } from 'antd/lib/upload/interface';
import React, { useEffect, useState } from 'react';
import './index.css';

const VideoUploadAndSelect: React.FC<any> = (props) => {
    const [showAddButton, updateAddButton] = useState(props.preVideo ? false : true);
    const [showSelectModal, updateSelectModal] = useState(false);
    const [lastSelect, updateLastSelect] = useState<any>(null);
    const [lastSelectVideo, updateLastSelectVideo] = useState<any>(null);
    const [assetData, updateAssetData] = useState<any>({
        data: [],
        total: 0,
        pageSize: 10,
        current: 0,
    });
    const [fileList, updateFileList] = props.preVideo

        ? useState<any>([
            {
                uid: Date.now(),
                percent: 100,
                url: URLS.SERVER_PICTURE_URL + props.preVideo,
                status: 'done',
            },
        ])
        : useState<any>([]);
    useEffect(() => {
        if (fileList.length > 0 && fileList[0].url && fileList[0].url.endsWith(props.preVideo)) {
            return;
        }
        if (props.preVideo && props.preVideo.length > 0) {
            updateFileList([
                {
                    uid: Date.now(),
                    percent: 100,
                    url: URLS.SERVER_PICTURE_URL + props.preVideo,
                    status: 'done',
                },
            ]);
            updateAddButton(false);
        }
    });
    //自定义上传方法
    const customRequestUpload = async (option: RcCustomRequestOptions) => {
        var data = new FormData();
        updateFileList([
            {
                uid: option.file.uid,
                percent: 99,
                status: 'uploading',
            },
        ]);
        data.append('filename', option.file);
        data.append('type', '2');
        var result = await request('/api/utils/v1/upload', {
            method: 'POST',
            data: data,
        }).catch((ex) => { });
        if (result) {
            var asset = await APIS.AssetAPI.CreateNewAsset({
                url: result.data,
                type: Const.ASSET_TYPE.VIDEO_TYPE,
            }).catch(() => { });
            updateFileList([
                {
                    uid: option.file.uid,
                    percent: 100,
                    url: URLS.SERVER_PICTURE_URL + asset.data?.url,
                    status: asset.data ? 'done' : 'error',
                },
            ]);
            props.handleVideoChange?.(result.data);
        }
    };
    const renderSelectPopup = () => (
        <div style={{}}>
            <Input.Search placeholder="请输入搜索的视频"></Input.Search>
            <Divider></Divider>
            <List
                style={{ width: '700px' }}
                dataSource={assetData.data}
                pagination={{
                    current: assetData.current,
                    total: assetData.total,
                    pageSize: 8,
                    onChange: async (page, count) => {
                        var result = await APIS.AssetAPI.GetAssetList({ current: page, pageSize: count }, 2);
                        updateAssetData(result);
                    },
                }}
                grid={{
                    gutter: 1,
                    xs: 2,
                    sm: 3,
                    md: 4,
                    lg: 4,
                    xl: 4,
                    xxl: 4,
                }}
                footer={
                    <Space>
                        <Button
                            disabled={!lastSelect}
                            onClick={async () => {
                                updateSelectModal(false);
                                updateFileList([
                                    {
                                        uid: Date.now() + '',
                                        url: URLS.SERVER_PICTURE_URL + lastSelectVideo.url,
                                        status: 'done',
                                    },
                                ]);
                                updateAddButton(false);
                                props.handleImageChange?.(lastSelectVideo.url);

                            }}
                        >
                            确定
            </Button>
                        <Button>取消</Button>
                    </Space>
                }
                renderItem={(item: any, index) => (
                    <div key={index} className="image-card">
                        <img
                            alt="example"
                            src={URLS.SERVER_PICTURE_URL + item.url}
                            onClick={(event) => {
                                var img = event.target as HTMLImageElement;
                                if (lastSelect) {
                                    lastSelect.parentElement?.classList.remove('ant-card-body-img-select');
                                }
                                updateLastSelect(img);

                                updateLastSelectVideo(item);
                                img.parentElement?.classList.add('ant-card-body-img-select');
                            }}
                        />
                        <div
                            className="image-title"
                            style={{
                                // position: ,
                                top: '-30px',
                                width: '100%',
                                height: '30px',
                                backgroundColor: 'rgba(0,0,0,0.4)',
                            }}
                        >
                            <span>测试视频</span>
                        </div>
                    </div>
                )}
            ></List>
        </div>
    );
    return (
        <div style={{ display: 'flex' }}>
            <Upload
                accept=".mp4"
                className="uplaod-image-btn"
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: true }}
                multiple={false}
                name="logo"
                action="/upload.do"
                onRemove={() => {
                    updateAddButton(true);
                    updateFileList([]);
                    props.handleVideoChange?.(null);
                }}
                fileList={fileList}
                customRequest={customRequestUpload}
                onChange={({ fileList }) => {
                    updateAddButton(fileList.length === 0);
                    updateFileList(fileList);
                }}
                listType="picture-card"
            >
                {showAddButton ? <Button icon={<PlusOutlined />}></Button> : null}
            </Upload>
            <Popover
                content={renderSelectPopup}
                title="请选择一个视频"
                trigger="click"
                visible={showSelectModal}
                onVisibleChange={(visible) => updateSelectModal(visible)}
            >
                <Button
                    onClick={async () => {
                        updateSelectModal(true);
                        var result = await APIS.AssetAPI.GetAssetList(
                            { current: 1, pageSize: 8 },
                            2,
                        ).catch(() => { });

                        updateAssetData(result);
                    }}
                    style={{ height: '104px', width: '104px', padding: '0px 0px' }}
                >
                    从列表中选取
                </Button>
            </Popover>
        </div>
    );
};

export default VideoUploadAndSelect;
